var express = require('express');			// express module
var app = express();						// initiating express app
var http = require('http');					// http module
var bodyParser = require('body-parser');	// body-parser module for reading request body
var fs = require('fs');						// fs module for handling file operations
var server = http.createServer(app);		// creating server
var io = require('socket.io');				// using sockets
var iosocket = io.listen(server);				// listening sockets
var formidable = require('formidable');		// file upload module
var util = require('util');
var qs = require('querystring');
// Initializing Variables
var nickname = [];
var i = [];
var x = [];
var online_member = [];
var temp1;
var socket_id;
var socket_data;
var files_array  = [];
var expiryTime = 8;
var routineTime = 1;

// server starting on port '8282'
server.listen(8282, function(){
	console.log('listening on *:8282');
});
// cofiguring body-parser
app.use(bodyParser.json({	// setting json limit 	
    limit: 1024 * 10000
}));
app.use(bodyParser.text({ 	// setting text limit
    limit: 1024 * 10000
}));
app.use(bodyParser.raw({ 	// setting raw limit
    limit: 1024 * 10000
}));
app.use(bodyParser.urlencoded({		// setting url encoding
    extended: true
}));
//static file configuration
app.use(express.static(__dirname + '/public'));

// CORS Issue Fix
app.use(function(req, res, next) {														
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

//sockets handling
iosocket.on('connection', function(socket){
	// creating new user if nickname doesn't exists
	socket.on('new user', function(req , callback){
		console.log("nickname.length:"+Object.keys(nickname).length);
	    //==========验证用户名及密码是否正确=============
		//这是需要提交的数据
		var username = req.username ;
		var password = req.password ;
		var userAvatar = req.userAvatar ;
		console.log("request login :" + username);
		var post_data = {  
		    username: username,  
		    password: password
		};
		var content = qs.stringify(post_data);
		var options = {  
		    hostname: '127.0.0.1',
		    port: 8080,
		    path: '/bkend/user/login',
		    method: 'POST',  
		    headers: {
		        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
		    }
		};
		var req = http.request(options, function (res) {
		    //console.log('STATUS: ' + res.statusCode);  
		    //console.log('HEADERS: ' + JSON.stringify(res.headers));  
		    res.setEncoding('utf8');  
		    res.on('data', function (chunk) {
		        console.log('BODY: ' + chunk);
		        var resultJson = JSON.parse(chunk);
		        if(resultJson.code == 200)
	        	{
		        	//server 端记录
					socket.username = username;
					socket.userAvatar = userAvatar;
					nickname[username] = socket;
		        	callback({success:true,sessionId:resultJson.data.sessionId});
	        	}
		        else
		        {
		        	callback({success:false,msg:resultJson.msg});
		        }
		    });
		});  
		req.on('error', function (e) {  
		    console.log('problem with request: ' + e.message);
		});  
		// write data to request body
		req.write(content);
		//req.end 之后,请求表示结束,后续回调中无法获取到req中的参数
		req.end();
	});

	// sending online members list
	socket.on('get-online-members', function(data){
		var online_member = [];
		i = Object.keys(nickname);
		console.log(i.length);
		console.log("=====请求get-online-members , i: "+i);
		for(var j=0;j<i.length;j++ )
		{
			socket_id = i[j];
			socket_data = nickname[socket_id];
			temp1 = {"username": socket_data.username, "userAvatar":socket_data.userAvatar};
			online_member.push(temp1);
		}
		iosocket.sockets.emit('online-members', online_member);
	});

	// sending new message
	socket.on('send-message', function(data, callback){
		if (nickname[data.username]) {
			if(data.hasMsg){
				iosocket.sockets.emit('new message', data);
				callback({success:true});	
			}else if(data.hasFile){
				if(data.istype == "image"){
					socket.emit('new message image', data);
					callback({success:true});
				} else if(data.istype == "music"){
					socket.emit('new message music', data);
					callback({success:true});
				} else if(data.istype == "PDF"){
					socket.emit('new message PDF', data);
					callback({success:true});
				}
			}else{
				callback({ success:false});
			}
		}		
	});
	
	// disconnect user handling 
	socket.on('disconnect', function () {	
		delete nickname[socket.username];
		online_member = [];
		x = Object.keys(nickname);
		for(var k = 0 ; k < x.length ; k++ )
    	{
        	socket_id = x[k];
        	socket_data = nickname[socket_id];
        	temp1 = {"username": socket_data.username, "userAvatar":socket_data.userAvatar};
            online_member.push(temp1);
    	}
		iosocket.sockets.emit('online-members', online_member);
   	});
});